from rest_framework.exceptions import APIException
from myapp3.models import project_info,robox_info
from myapp.views import AuthcationView,Authcation_NomalView
from myapp3.serializers import RoboxSerializer, ProjectSerializer, ImageUploadSerializer,RoboxTipsSerializer,ProjectTipsSerializer
from myapp3.serializers import RobotVersionSerializer,FaqSerializer,FaqImageUploadSerializer
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import *
from itertools import groupby
from myapp3.models import Image,Picture
from django.views.decorators.csrf import csrf_exempt

# def index(request):
#     return render(request, "index.html")

class RobotInfoView(APIView):
    authentication_classes = [AuthcationView]
    def get(self, request):
        origin_data = robox_info.objects.all().order_by("id")
        serialized_data = RoboxSerializer(origin_data, many=True)
        return Response(serialized_data.data)

    def post(self, request):
        verified_data = RoboxSerializer(data=request.data)
        if verified_data.is_valid():
            verified_data.save()
            return Response(verified_data.data)
        else:
            return Response(verified_data.errors)

    def options(self, request, *args, **kwargs):
        return Response('200')

class RoboxFilterView(APIView):
    authentication_classes = [Authcation_NomalView]
    def get(self, request, pk):
        robox_infos = robox_info.objects.get(pk=pk)
        serializer = RoboxSerializer(robox_infos)
        return Response(serializer.data)

    def delete(self, request, pk):
        robox_info.objects.get(pk=pk).delete()
        return Response('ok')

    def put(self, request, pk):
        robox_infos = robox_info.objects.get(pk=pk)
        verified_data = RoboxSerializer(data=request.data, instance=robox_infos)
        if verified_data.is_valid():
            verified_data.save()
            return Response(verified_data.data)
        else:
            return Response(verified_data.errors)

class ProjectInfoView(APIView):
    authentication_classes = [AuthcationView]
    def get(self, request):
        origin_data = project_info.objects.all().order_by("id")
        serialized_data = ProjectSerializer(origin_data, many=True)
        return Response(serialized_data.data)

    def post(self, request):
        verified_data = ProjectSerializer(data=request.data)
        if verified_data.is_valid():
            verified_data.save()
            return Response(verified_data.data)
        else:
            return Response(verified_data.errors)

class ProjectFilterView(APIView):
    authentication_classes = [Authcation_NomalView]
    def get(self,request,pk):

        project_infos = project_info.objects.get(pk=pk)
        serializer = ProjectSerializer(project_infos)
        return Response(serializer.data)

    def delete(self,request,pk):
        project_info.objects.get(pk=pk).delete()
        return Response('ok')

    def put(self, request, pk):
        project_infos = project_info.objects.get(pk=pk)
        verified_data = ProjectSerializer(data=request.data, instance=project_infos)
        if verified_data.is_valid():
            # with transaction.atomic():
            verified_data.save()
            return Response(verified_data.data)
        else:
            return Response(verified_data.errors)

# import time
# import hashlib
class ImageUpload(APIView):
    @csrf_exempt
    def post(self, request, *args, **kwargs):

        image = request.FILES['image']
        data = request.data
        serial = ImageUploadSerializer(data={"robot_id_id": data["id"],"image": image})
        if serial.is_valid():
            print("校验成功")
        else:
            raise APIException("参数校验失败")
        Image.objects.update_or_create(robot_id_id=data["id"] ,defaults={'image': image})
        imagesurl = Image.objects.filter(robot_id_id=data["id"])
        serialized_data = ImageUploadSerializer(imagesurl, many=True)
        return Response(serialized_data.data)
        # serial.save(
        # image = serial.validated_data.get("image")
        # new_image = Image(image=image)
        # imageName = str(new_image.image.name)
        # location = str(imageName).find('.')
        # extension = imageName[location:]
        #
        # name = imageName[:location]
        # namestring = name+str(time.time())
        # md5 = hashlib.md5(namestring.encode('utf-8')).hexdigest()
        # new_image.image.name = md5[:10] + extension
        # new_image.save( )

    def get(self, request, *args, **kwargs):
        data = request.data
        imagesurl = Image.objects.filter(robot_id_id=data["id"])
        serialized_data = ImageUploadSerializer(imagesurl, many=True)
        return Response(serialized_data.data)

    def delete(self, request, *args, **kwargs):
        try:
            token = request.META.get('HTTP_AUTHORIZATION')  # 将token放入请求头中
            print(token)
        except Exception as e:
            ret = {'code': 1007, 'msg': '未获取到token，请重新登陆'}
            raise APIException(ret)
        user_name = [''.join(list(g)) for k, g in groupby(token, key=lambda x: x.isdigit())]
        username = user_name[3].split('@')[0]
        print(username)
        if username  not in ['sun','hexu']:
            ret = {'code': 1008, 'msg': '该用户无权限! '}
            raise APIException(ret)
        data = request.data
        print(data)
        Image.objects.filter(robot_id_id=data["id"]).delete()
        return Response('delete ok')


class PicuploadView(APIView):
    @csrf_exempt
    def post(self, request, *args, **kwargs):
        data = request.data
        pic = request.FILES.get('pic')  # 获取图片
        img = pic.read()  # 将图片转为二进制  ，可直接存储在数据库中
        Picture.objects.update_or_create(robot_id_id=data["id"] ,defaults={'pic': img})
        return Response('ok')

    def get(self, request, *args, **kwargs):
        data = request.data
        imagesurl = Image.objects.filter(robot_id_id=data["id"])
        serialized_data = ImageUploadSerializer(imagesurl, many=True)
        return Response(serialized_data.data)

class RoboxTipsView(APIView):
    authentication_classes = [AuthcationView]
    def get(self, request):
        origin_data = robox_infoTips.objects.all().order_by("id")
        serialized_data = RoboxTipsSerializer(origin_data, many=True)
        return Response(serialized_data.data)

    def post(self, request):
        verified_data = RoboxTipsSerializer(data=request.data)
        if verified_data.is_valid():
            verified_data.save()
            return Response(verified_data.data)
        else:
            return Response(verified_data.errors)

class RoboxTipsFilterView(APIView):
    authentication_classes = [Authcation_NomalView]
    def get(self,request,pk):

        robox_tipinfos = robox_infoTips.objects.get(pk=pk)
        serializer = RoboxTipsSerializer(robox_tipinfos)
        return Response(serializer.data)

    def delete(self,request,pk):
        robox_infoTips.objects.get(pk=pk).delete()
        return Response('ok')

    def put(self, request, pk):
        robox_tipinfos = robox_infoTips.objects.get(pk=pk)
        verified_data = RoboxTipsSerializer(data=request.data, instance=robox_tipinfos)
        if verified_data.is_valid():
            # with transaction.atomic():
            verified_data.save()
            return Response(verified_data.data)
        else:
            return Response(verified_data.errors)

class ProjectTipsView(APIView):
    authentication_classes = [AuthcationView]
    def get(self, request):
        origin_data = project_infoTips.objects.all().order_by("id")
        serialized_data = ProjectTipsSerializer(origin_data, many=True)
        return Response(serialized_data.data)

    def post(self, request):
        verified_data = ProjectTipsSerializer(data=request.data)
        if verified_data.is_valid():
            verified_data.save()
            return Response(verified_data.data)
        else:
            return Response(verified_data.errors)

class ProjectTipsFilterView(APIView):
    authentication_classes = [Authcation_NomalView]
    def get(self,request,pk):

        project_tipinfos = robox_infoTips.objects.get(pk=pk)
        serializer = ProjectTipsSerializer(project_tipinfos)
        return Response(serializer.data)

    def delete(self,request,pk):
        project_infoTips.objects.get(pk=pk).delete()
        return Response('ok')

    def put(self, request, pk):
        project_tipinfos = project_infoTips.objects.get(pk=pk)
        verified_data = ProjectTipsSerializer(data=request.data, instance=project_tipinfos)
        if verified_data.is_valid():
            # with transaction.atomic():
            verified_data.save()
            return Response(verified_data.data)
        else:
            return Response(verified_data.errors)

class RobotVersionView(APIView):
    authentication_classes = [AuthcationView]
    def get(self, request):
        origin_data = robot_version.objects.all().order_by("-id")
        serialized_data = RobotVersionSerializer(origin_data, many=True)
        return Response(serialized_data.data)

    def post(self, request):
        verified_data = RobotVersionSerializer(data=request.data)
        if verified_data.is_valid():
            verified_data.save()
            return Response(verified_data.data)
        else:
            return Response(verified_data.errors)

class RobotVersionFilterView(APIView):
    authentication_classes = [Authcation_NomalView]
    def get(self,request,pk):

        datas = robot_version.objects.get(pk=pk)
        serializer = RobotVersionSerializer(datas)
        return Response(serializer.data)

    def delete(self,request,pk):
        robot_version.objects.get(pk=pk).delete()
        return Response('ok')

    def put(self, request, pk):
        datas = robot_version.objects.get(pk=pk)
        verified_data = RobotVersionSerializer(data=request.data, instance=datas)
        if verified_data.is_valid():
            # with transaction.atomic():
            verified_data.save()
            return Response(verified_data.data)
        else:
            return Response(verified_data.errors)


class FaqView(APIView):
    # authentication_classes = [AuthcationView]
    def get(self, request):
        origin_data = faq.objects.all().order_by("-id")
        serialized_data = FaqSerializer(origin_data, many=True)
        return Response(serialized_data.data)

    def post(self, request):
        verified_data = FaqSerializer(data=request.data)
        if verified_data.is_valid():
            verified_data.save()
            return Response(verified_data.data)
        else:
            return Response(verified_data.errors)

class FaqFilterView(APIView):
    # authentication_classes = [Authcation_NomalView]
    def get(self,request,pk):
        datas = faq.objects.get(pk=pk)
        serializer = FaqSerializer(datas)
        return Response(serializer.data)

    def delete(self,request,pk):
        faq.objects.get(pk=pk).delete()
        return Response('ok')

    def put(self, request, pk):
        datas = faq.objects.get(pk=pk)
        verified_data = FaqSerializer(data=request.data, instance=datas)
        if verified_data.is_valid():
            # with transaction.atomic():
            verified_data.save()
            return Response(verified_data.data)
        else:
            return Response(verified_data.errors)

class FaqImageView(APIView):
    @csrf_exempt
    # authentication_classes = [AuthcationView]
    def post(self, request, *args, **kwargs):

        image = request.FILES['image']
        data = request.data
        serial = FaqImageUploadSerializer(data={"problem_id_id": data["problem_id_id"],"image": image})
        if serial.is_valid():
            print("校验成功")
        else:
            raise APIException("参数校验失败")
        faq_image.objects.create(problem_id_id=data["problem_id_id"] ,image= image)
        imagesurl = faq_image.objects.filter(problem_id_id=data["problem_id_id"])
        serialized_data = FaqImageUploadSerializer(imagesurl, many=True)
        return Response(serialized_data.data)

    def get(self, request, *args, **kwargs):
        data = request.data
        imagesurl = faq_image.objects.filter(problem_id_id=data["problem_id_id"])
        serialized_data = FaqImageUploadSerializer(imagesurl, many=True)
        return Response(serialized_data.data)

    def delete(self, request, *args, **kwargs):
        try:
            token = request.META.get('HTTP_AUTHORIZATION')  # 将token放入请求头中
            print(token)
        except Exception as e:
            ret = {'code': 1007, 'msg': '未获取到token，请重新登陆'}
            raise APIException(ret)
        user_name = [''.join(list(g)) for k, g in groupby(token, key=lambda x: x.isdigit())]
        username = user_name[3].split('@')[0]
        print(username)
        if username  not in ['sun','hexu']:
            ret = {'code': 1008, 'msg': '该用户无权限! '}
            raise APIException(ret)
        data = request.data
        try :
            image_id = data["image_id"]
            faq_image.objects.filter(problem_id_id=data["problem_id_id"],id=image_id).delete()
        except:
            faq_image.objects.filter(problem_id_id=data["problem_id_id"]).delete()

        nowdata=faq_image.objects.filter(problem_id_id=data["problem_id_id"])
        serialized_data = FaqImageUploadSerializer(nowdata, many=True)
        return Response(serialized_data.data)